package com.ysd.lis.service.lab.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.bac.BacImageResult;
import com.ysd.lis.entity.bac.BacPublisSecReport;
import com.ysd.lis.entity.lab.LabRptGroup;
import com.ysd.lis.mapper.bac.BacImageResultMapper;
import com.ysd.lis.mapper.bac.BacPublisSecReportMapper;
import com.ysd.lis.mapper.lab.LabRptGroupMapper;
import com.ysd.lis.mapper.pub.PubReportMapper;
import com.ysd.lis.mapper.pub.PubReportRulesMapper;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.ReportPageParam;
import com.ysd.lis.request.bac.BacRptOverviewItemDto;
import com.ysd.lis.service.*;
import com.ysd.lis.service.lab.LabProcessSetService;
import com.ysd.lis.service.lab.PubReportService;
import com.ysd.lis.service.lab.WlConfigService;
import com.ysd.util.IncrementalNumberGenerator;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.SYS_REPORT 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2023-11-06
 */
@Service
public class PubReportServiceImpl extends ServiceImpl<PubReportMapper, PubReport> implements PubReportService {
    @Autowired
    PubReportMapper pubReportMapper;
    @Autowired
    BacPublisSecReportMapper bacPublisSecReportMapper;
    @Autowired
    PubReportService pubReportService;
    @Autowired
    SysModuleMapper moduleMapper;
    @Autowired
    SysPointsMapper pointsMapper;
    @Autowired
    SysMenuMapper menuMapper;
    @Autowired
    SysBasDictDetailMapper basDictDetailMapper;
    @Autowired
    SysBasDictMapper basDictMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    PubReportRulesMapper pubReportRulesMapper;
    @Autowired
    LabRptGroupMapper labRptGroupMapper;
    @Autowired
    SysModuleService sysModuleService;
    @Autowired
    SysBasDictService sysBasDictService;
    @Autowired
    SysInterfaceService sysInterfaceService;
    @Autowired
    SysRuleSetService sysRuleSetService;

    @Autowired
    SysParamService sysParamService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysUserService sysUserService;
    @Autowired
    private WlConfigService wlConfigService;
    @Autowired
    LabProcessSetService processSetService;
    @Autowired
    BacImageResultMapper bacImageResultMapper;

    public Result getPageList(ReportPageParam reportPageParam) {

        if (StringUtils.isNotBlank(reportPageParam.getDictDetailCode()) && StringUtils.isNotBlank(reportPageParam.getDictDetailValue())) {
            LambdaQueryWrapper<SysBasDictDetail> basDictDetailWrapper = new LambdaQueryWrapper<>();
            basDictDetailWrapper.eq(SysBasDictDetail::getDelFlag, "0").eq(SysBasDictDetail::getCode, reportPageParam.getDictDetailCode()).eq(SysBasDictDetail::getValue, reportPageParam.getDictDetailValue());
            List<SysBasDictDetail> basDictDetails = basDictDetailMapper.selectList(basDictDetailWrapper);
            if (ToolsUtils.isNotEmpty(basDictDetails)){
                reportPageParam.setPointsId(basDictDetails.get(0).getCommonId());
            }
        }
        if (StringUtils.isNotBlank(reportPageParam.getCode())) {
            LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysMenu::getDelFlag, 0);
            lambdaQueryWrapper.eq(SysMenu::getCode, reportPageParam.getCode());
            List<SysMenu> sysMenus = menuMapper.selectList(lambdaQueryWrapper);
            reportPageParam.setModuleId(CollectionUtil.isNotEmpty(sysMenus) ? sysMenus.get(0).getModuleId() : null);
        }


        Map returnMap = new HashMap<>();
        LambdaQueryWrapper<PubReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<PubReport> page = new Page<PubReport>();
        page.setCurrent(reportPageParam.getPageIndex());
        page.setSize(reportPageParam.getPageSize());
        lambdaQueryWrapper.eq(PubReport::getDelFlag, 0);
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(reportPageParam.getType())) {
            return Result.fail("获取报表的类型务必传入", returnMap);
        }
        if (ToolsUtils.isNotEmpty(sysUser)) {
            lambdaQueryWrapper.eq(PubReport::getOrgId, sysUser.getOrgId());
        }
        if (StringUtils.isNotBlank(reportPageParam.getModuleId())) {
            lambdaQueryWrapper.eq(PubReport::getModuleId, reportPageParam.getModuleId());
        }
        if (StringUtils.isNotBlank(reportPageParam.getMenuId())) {
            lambdaQueryWrapper.eq(PubReport::getMenuId, reportPageParam.getMenuId());
        }
        if (StringUtils.isNotBlank(reportPageParam.getCommonId())) {
            lambdaQueryWrapper.eq(PubReport::getCommonId, reportPageParam.getCommonId());
        }
        if (StringUtils.isNotBlank(reportPageParam.getPointsId())) {
            lambdaQueryWrapper.eq(PubReport::getPointsId, reportPageParam.getPointsId());
        }
        if (StringUtils.isNotBlank(reportPageParam.getKeywords())) {
            lambdaQueryWrapper.like(PubReport::getName, reportPageParam.getKeywords());
        }
        lambdaQueryWrapper.eq(PubReport::getType, reportPageParam.getType());
        lambdaQueryWrapper.orderByDesc(PubReport::getParentId);
        Page<PubReport> reportPageList = pubReportMapper.selectPage(page, lambdaQueryWrapper);
        List<PubReport> listPubReport = reportPageList.getRecords();
        if (ToolsUtils.isNotEmpty(listPubReport)) {
            for (PubReport pubReport : listPubReport) {
                if (ToolsUtils.isNotEmpty(pubReport.getModuleId())) {
                    SysModule sysModule = moduleMapper.selectById(pubReport.getModuleId());
                    pubReport.setModuleName(sysModule.getName());
                }
                if (ToolsUtils.isNotEmpty(pubReport.getPointsId())) {
                    LambdaQueryWrapper<SysBasDictDetail> basDictDetailWrapper = new LambdaQueryWrapper<>();
                    basDictDetailWrapper.eq(SysBasDictDetail::getDelFlag, "0").eq(SysBasDictDetail::getCode, "pointsName").eq(SysBasDictDetail::getCommonId, pubReport.getPointsId());
                    List<SysBasDictDetail> basDictDetails = basDictDetailMapper.selectList(basDictDetailWrapper);
                    if (ToolsUtils.isNotEmpty(basDictDetails)) {
                        pubReport.setPointsName(basDictDetails.get(0).getValue());
                    }
//                    SysPoints points =   pointsMapper.selectById(pubReport.getPointsId());
//                    pubReport.setPointsName(points.getTitle());
                }
                if (ToolsUtils.isNotEmpty(pubReport.getMenuId())) {
                    SysMenu menu = menuMapper.selectById(pubReport.getMenuId());
                    pubReport.setMenuName(menu.getTitle());
                }
//                if(ToolsUtils.isNotEmpty(pubReport.getCommonId())){
//                    LambdaQueryWrapper<SysBasDictDetail> basDictDetailWrapper = new LambdaQueryWrapper<>();
//                    basDictDetailWrapper.eq(SysBasDictDetail::getDelFlag,"0") .eq(SysBasDictDetail::getCode,"name").eq(SysBasDictDetail::getCommonId,pubReport.getCommonId());
//                    List<SysBasDictDetail> basDictDetails =   basDictDetailMapper.selectList(basDictDetailWrapper);
//                    if(ToolsUtils.isNotEmpty(basDictDetails)){
//                        pubReport.setReportGroupName(basDictDetails.get(0).getValue());
//                    }
//                }
            }
        }
        reportPageList.setRecords(listPubReport);
        // 获取顶层节点（parentId为null或0）
        //queryWrapper.eq(PubReport::getDelFlag, "0");
        //List<PubReport> pubReportList = pubReportMapper.selectList(queryWrapper);
//        if (ToolsUtils.isNotEmpty(pubReportList)) {
//            if (reportPageParam.getType().equals("0")) {
//                pubReportList.forEach(a -> {
//                    if (StringUtils.isBlank(a.getParentId())) {
//                        a.setChildren(this.getChildrenPoints(a, pubReportList));
//                        returnList.add(a);
//                    }
//                });
//
//            } else if (reportPageParam.getType().equals("1")) {
//                pubReportList.forEach(a -> {
//                    if (StringUtils.isBlank(a.getParentId())) {
//                        a.setChildren(this.getChildrenMenu(a, pubReportList));
//                        returnList.add(a);
//                    }
//                });
//
//            }else if(reportPageParam.getType().equals("2")){
//                pubReportList.forEach(a -> {
//                    if (StringUtils.isBlank(a.getParentId())) {
//                        a.setChildren(this.getChildrenReportInfoInstrument(a, pubReportList));
//                        returnList.add(a);
//                    }
//                });
//            }
//        }

        // 将树状结构赋值给logPageList的records属性
        //reportPageList.setRecords(returnList);
        returnMap.put("reportList", reportPageList);
        return Result.succ(1, "获取信息成功", returnMap);
    }

    @Override
    public Result addReportBusiness(PubReport pubReport) {
        if (ToolsUtils.isEmpty(pubReport)) {
            return Result.fail("新增报表，入参异常");
        }
        //先查询报表数据中是否有此名称的报表，不能存在报表名重复的数据
        LambdaQueryWrapper<PubReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PubReport::getName, pubReport.getName())
                .eq(PubReport::getDelFlag, 0);
        int count = this.count(queryWrapper);
        if (count > 0) {
            return Result.fail("此报表名称已存在，添加失败！");
        }
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(sysUser)) {
            return Result.fail("从Redis获取用户数据为NULL: 请检查redis相关配置");
        }
        if (ToolsUtils.isEmpty(sysUser.getOrgId())) {
            return Result.fail("获取机构ID异常 ： 请给登录用户设置所属机构");
        }
        pubReport.setOrgId(sysUser.getOrgId());
        pubReport.setType(pubReport.getType());
        pubReport.setCode(IncrementalNumberGenerator.generateIncrementalNumber());
        //pubReport.setParentName(pubReport.getName());
        int insert = pubReportMapper.insert(pubReport);
        if(insert > 0){
            return Result.succ("新增成功");
        }else {
            return Result.fail("新增失败");
        }
    }

    @Override
    public Result saveAsReportBusiness(PubReport pubReport) {
        PubReport addPubReport = new PubReport();
        if (ToolsUtils.isEmpty(pubReport)) {
            return Result.fail("新增报表，入参异常");
        }
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(sysUser)) {
            return Result.fail("从Redis获取用户数据为NULL: 请检查redis相关配置");
        }
        if (ToolsUtils.isEmpty(sysUser.getOrgId())) {
            return Result.fail("获取机构ID异常 ： 请给登录用户设置所属机构");
        }
        String name = pubReport.getName();
        addPubReport.setOrgId(sysUser.getOrgId());
        addPubReport.setType(pubReport.getType());
        if (ToolsUtils.isNotEmpty(pubReport.getParentId())) {
            addPubReport.setParentId(pubReport.getParentId());
            addPubReport.setParentName(pubReport.getParentName());
            pubReport.setName(name + "(" + pubReport.getParentName() + ")");
        } else {
            addPubReport.setParentId(pubReport.getId());
            addPubReport.setParentName(pubReport.getSaveAsName());
            pubReport.setName(name + "(" + pubReport.getSaveAsName() + ")");
        }

        addPubReport.setCode(IncrementalNumberGenerator.generateIncrementalNumber());
        addPubReport.setModuleId(pubReport.getModuleId());
        addPubReport.setName(pubReport.getName());
        addPubReport.setPaperSize(pubReport.getPaperSize());
        addPubReport.setReportTemplate(pubReport.getReportTemplate());
        PubReport pubReport1 = pubReportMapper.selectById(pubReport.getId());
        if (pubReport1 != null) {
            addPubReport.setReportTemplate(pubReport1.getReportTemplate());
        }

        if (pubReport.getType().equals("0")) {
            addPubReport.setPointsId(pubReport.getPointsId());
        } else if (pubReport.getType().equals("1")) {
            addPubReport.setMenuId(pubReport.getMenuId());
        } else if (pubReport.getType().equals("2")) {
            addPubReport.setCommonId(pubReport.getCommonId());
        }
        pubReportMapper.insert(addPubReport);
        return Result.fail("另存为成功", addPubReport);
    }

    @Override
    public Result deleteReport(PubReport pubReport) {

        if (ToolsUtils.isEmpty(pubReport)) {
            return Result.fail("删除报表，入参异常");
        }
//        SysUser sysUser = RedisUserManager.getUser();
//        if (ToolsUtils.isEmpty(sysUser)) {
//            return Result.fail("从Redis获取用户数据为NULL: 请检查redis相关配置");
//        }
//        if (ToolsUtils.isEmpty(sysUser.getOrgId())){
//            return Result.fail("获取机构ID异常 ： 请给登录用户设置所属机构");
//        }
        LambdaQueryWrapper<PubReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PubReport::getParentId, pubReport.getId()).eq(PubReport::getDelFlag, 0);
        List<PubReport> list = pubReportMapper.selectList(queryWrapper);
        if (list.size() > 0) {
            return Result.fail("请先删除子模版，方可删除基础模版");
        }
        PubReport updatePub = new PubReport();
        updatePub.setId(pubReport.getId());
        updatePub.setDelFlag(1);
        pubReportMapper.updateById(updatePub);
        return Result.succ("删除成功");
    }

    @Override
    @Transactional
    public Result updateUse(PubReport pubReport) {
        if (ToolsUtils.isEmpty(pubReport)) {
            return Result.fail("设置报表，入参异常");
        }
     /*   LambdaUpdateWrapper<PubReport> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if (ToolsUtils.isNotEmpty(pubReport.getPointsId())) {//业务表单
            lambdaUpdateWrapper.eq(PubReport::getPointsId, pubReport.getPointsId());
        }
        if (ToolsUtils.isNotEmpty(pubReport.getMenuId())) {//报表
            lambdaUpdateWrapper.eq(PubReport::getMenuId, pubReport.getMenuId());
            //相应的去修改菜单中被使用的报表模版与报表路径
            LambdaUpdateWrapper<SysMenu> menuUpdateWrapper = new LambdaUpdateWrapper<>();
            String reportUrl = "";
            if (pubReport.getIsUse().equals("0")) {
                reportUrl = "?id=" + pubReport.getId() + "&name=" + pubReport.getName();
                menuUpdateWrapper.set(SysMenu::getReportId, pubReport.getId());
            } else {
                menuUpdateWrapper.set(SysMenu::getReportId, null);
            }
            menuUpdateWrapper.eq(SysMenu::getId, pubReport.getMenuId()).set(SysMenu::getReportUrl, reportUrl);
            menuMapper.update(null, menuUpdateWrapper);
        }
        if (ToolsUtils.isNotEmpty(pubReport.getCommonId())){ //报告
            lambdaUpdateWrapper.eq(PubReport::getCommonId,pubReport.getCommonId());
        }
        if (!pubReport.getType().equals("2")) {
            lambdaUpdateWrapper.eq(PubReport::getType, pubReport.getType()).set(PubReport::getIsUse, "1");
            pubReportMapper.update(null, lambdaUpdateWrapper);
        }*/

        PubReport updatePub = new PubReport();
        updatePub.setId(pubReport.getId());
        updatePub.setIsUse(pubReport.getIsUse());
        pubReportMapper.updateById(updatePub);
        return Result.succ("设置成功");
    }

    @Override
    public Result getReportById(PubReport pubReport) {
        if (ToolsUtils.isEmpty(pubReport)) {
            return Result.fail("设置成功");
        }
        PubReport retPubReport = pubReportMapper.selectById(pubReport.getId());
        return Result.succ(retPubReport);
    }

    @Override
    public Result saveBatch(PubReport pubReport) {
        if (ToolsUtils.isEmpty(pubReport)) {
            return Result.fail("入参不可为空");
        }

        if (ToolsUtils.isEmpty(pubReport.getType())) {
            return Result.fail("无法确认被传的文件属于那种报表类型，请检查type入参是否为空");
        }
        String type = pubReport.getType();
        if (ToolsUtils.isEmpty(pubReport.getMenuId()) && ToolsUtils.isEmpty(pubReport.getPointsId()) && ToolsUtils.isEmpty(pubReport.getCommonId())) {
            return Result.fail("请点击选中左侧菜单栏中的相关项");
        }
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(sysUser)) {
            return Result.fail("从Redis获取用户数据为NULL: 请检查redis相关配置");
        }
        if (ToolsUtils.isEmpty(sysUser.getOrgId())) {
            return Result.fail("获取机构ID异常 ： 请给登录用户设置所属机构");
        }
        pubReport.setOrgId(sysUser.getOrgId());
        pubReport.setPaperSize("A4"); //默认为A4
        pubReport.setCode(IncrementalNumberGenerator.generateIncrementalNumber());
        if (type.equals("0")) { //业务表单类型
            if (ToolsUtils.isNotEmpty(pubReport.getPointsId())) {//存储到相应的模块与功能中
                //根据功能id获取所属的模块
                SysPoints points = pointsMapper.selectById(pubReport.getPointsId());
                pubReport.setModuleId(points.getModuleId());
            }
        } else if (type.equals("1")) {
            if (ToolsUtils.isNotEmpty(pubReport.getMenuId())) {//存储到相应的模块与功能中
                //根据功能id获取所属的模块
                SysMenu menu = menuMapper.selectById(pubReport.getMenuId());
                pubReport.setModuleId(menu.getModuleId());
            }
        } else if (type.equals("2")) {
            //仪器报表暂时没有相关逻辑
        }
        pubReportMapper.insert(pubReport);
        return Result.succ("上传成功");
    }

    @Override
    public Result getReportByAllReq(PubReport pubReport) {
        if (ToolsUtils.isEmpty(pubReport)) {
            Result.fail("入参不可为空");
        }
        LambdaQueryWrapper<PubReport> queryWrapper = new LambdaQueryWrapper<>();
        if (ToolsUtils.isNotEmpty(pubReport.getMenuId())) {
            queryWrapper.eq(PubReport::getMenuId, pubReport.getMenuId());
        }
        if (ToolsUtils.isNotEmpty(pubReport.getModuleId())) {
            queryWrapper.eq(PubReport::getModuleId, pubReport.getModuleId());
        }
        if (ToolsUtils.isNotEmpty(pubReport.getType())) {
            queryWrapper.eq(PubReport::getType, pubReport.getType());
        }
        queryWrapper.eq(PubReport::getDelFlag, "0");
        List<PubReport> pubReportList = pubReportMapper.selectList(queryWrapper);
        return Result.succ(pubReportList);
    }

    @Override
    public Result getModuleAndDictFormList() {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isNotEmpty(dictResult)) {
            List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();
            if (ToolsUtils.isNotEmpty(data)) {
                JSONArray jsonArray = new JSONArray();

                for (Map<String, Object> map : data) {
                    JSONObject jsonObject = new JSONObject(map);
                    jsonArray.put(jsonObject);
                }
                JSONArray resultArray = convertJsonArray(jsonArray);
                return Result.succ(resultArray.toList());
            }
        }
        return Result.fail("请检查业务表单词典设置是否正确");
    }

    @Override
    public Result getFormDictList() {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isNotEmpty(dictResult)) {
            List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();
            return Result.succ(data);
        }
        return Result.fail("请检查业务表单词典设置是否正确");
    }

    @Override
    public Result getReportByCommonId(String commonId) {
        LambdaQueryWrapper<PubReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PubReport::getCommonId, commonId).eq(PubReport::getDelFlag, "0");
        queryWrapper.orderByDesc(PubReport::getParentId);
        List<PubReport> list = pubReportMapper.selectList(queryWrapper);
        try {
            if (ToolsUtils.isNotEmpty(list)) {
                for (PubReport pubReport : list) {
                    LambdaQueryWrapper<PubReportRules> queryReportRulesWrapper = new LambdaQueryWrapper<>();
                    queryReportRulesWrapper.select(PubReportRules::getRptGroup);
                    queryReportRulesWrapper.eq(PubReportRules::getDelFlag, "0").eq(PubReportRules::getReportCode, pubReport.getCode()).groupBy(PubReportRules::getRptGroup);
                    List<PubReportRules> reportRules = pubReportRulesMapper.selectList(queryReportRulesWrapper);
                    if (ToolsUtils.isNotEmpty(reportRules)) {
                        String rptGroups = "";
                        for (PubReportRules reportRule : reportRules) {
                            List<LabRptGroup> labRptGroups = labRptGroupMapper.selectList(new LambdaQueryWrapper<LabRptGroup>().eq(LabRptGroup::getRptGroup, reportRule.getRptGroup()));
                            String rptGroupName = CollectionUtil.isNotEmpty(labRptGroups) ? labRptGroups.get(0).getRptGroupName() : "";
                            rptGroups += "，" + rptGroupName;
                        }
                        pubReport.setRptGroups(rptGroups.substring(1));
                    }
                }
            }
        } catch (Exception exception) {
            //TODO
        }
        return Result.succ(list);
    }

    @Override
    public Result getReportByReportCode(String reportCode) {
        LambdaQueryWrapper<PubReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PubReport::getDelFlag, 0);
        queryWrapper.eq(PubReport::getPointsId, reportCode);
        queryWrapper.eq(PubReport::getIsUse, 1);
        List<PubReport> pubReports = pubReportMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(pubReports)) {
            return Result.fail("查询失败");
        }
        PubReport pubReport = pubReports.get(pubReports.size() - 1);/*取最后一条，一般 最后上传为最新*/
        if (pubReport == null) {
            return Result.fail("查询失败");
        }
        String id = pubReport.getId();
        return Result.succ(1, "查询成功", id);
    }

    @Autowired
    SysBasDictDetailMapper sysBasDictDetailMapper;

    @Override
    public Result getReportByDictDetailVaule(String detailVaule) {
        MPJLambdaWrapper<SysBasDictDetail> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysBasDictDetail.class).innerJoin(SysBasDict.class, "a", p -> p.eq(SysBasDict::getId, SysBasDictDetail::getPid).eq(SysBasDict::getDelFlag, 0)).innerJoin(SysBasDict.class, "b", p -> p.eq(SysBasDict::getId, SysBasDict::getPid).eq(SysBasDict::getCode, "YWBD").eq(SysBasDict::getDelFlag, 0)).eq(SysBasDictDetail::getValue, detailVaule).eq(SysBasDictDetail::getDelFlag, 0);
        List<SysBasDictDetail> dictList = sysBasDictDetailMapper.selectList(queryWrapper);
        if (ToolsUtils.isNotEmpty(dictList)) {
            SysBasDictDetail sysBasDictDetail = dictList.get(0);
            String commonId = sysBasDictDetail.getCommonId();
            LambdaQueryWrapper<PubReport> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(PubReport::getDelFlag, 0);
            queryWrapper1.eq(PubReport::getPointsId, commonId);
            queryWrapper1.eq(PubReport::getIsUse, 1);
            List<PubReport> pubReports = pubReportMapper.selectList(queryWrapper1);
            if (ToolsUtils.isNotEmpty(pubReports)) {
                PubReport pubReport = pubReports.get(pubReports.size() - 1);/*取最后一条，一般 最后上传为最新*/
                String id = pubReport.getId();
                return Result.succ(1, "查询成功", id);
            } else {
                return Result.fail("查询失败");
            }
        } else {
            return Result.fail("查询失败");
        }

    }

    @Override
    public PubReport getPubReportByDictDetailVaule(String detailVaule) {
        MPJLambdaWrapper<SysBasDictDetail> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysBasDictDetail.class).innerJoin(SysBasDict.class, "a", p -> p.eq(SysBasDict::getId, SysBasDictDetail::getPid).eq(SysBasDict::getDelFlag, 0)).innerJoin(SysBasDict.class, "b", p -> p.eq(SysBasDict::getId, SysBasDict::getPid).eq(SysBasDict::getCode, "YWBD").eq(SysBasDict::getDelFlag, 0)).eq(SysBasDictDetail::getValue, detailVaule).eq(SysBasDictDetail::getDelFlag, 0);
        List<SysBasDictDetail> dictList = sysBasDictDetailMapper.selectList(queryWrapper);
        if (ToolsUtils.isNotEmpty(dictList)) {
            SysBasDictDetail sysBasDictDetail = dictList.get(0);
            String commonId = sysBasDictDetail.getCommonId();
            LambdaQueryWrapper<PubReport> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(PubReport::getDelFlag, 0);
            queryWrapper1.eq(PubReport::getPointsId, commonId);
            queryWrapper1.eq(PubReport::getIsUse, 1);
            List<PubReport> pubReports = pubReportMapper.selectList(queryWrapper1);
            if (ToolsUtils.isNotEmpty(pubReports)) {
                PubReport pubReport = pubReports.get(pubReports.size() - 1);/*取最后一条，一般 最后上传为最新*/
                return pubReport;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public Result setIncludeImages(PubReport pubReport) {
        if (ToolsUtils.isEmpty(pubReport)) {
            return Result.fail("设置报表，入参异常");
        }
        if (ToolsUtils.isEmpty(pubReport.getId())) {
            return Result.fail("设置报表，入参异常");
        }
        LambdaUpdateWrapper<PubReport> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(PubReport::getIncludeImages, pubReport.getIncludeImages()).eq(PubReport::getId, pubReport.getId());
        pubReportMapper.update(new PubReport(), lambdaUpdateWrapper);
        return Result.succ("设置成功");
    }


    @Override
    public Result getReportIdByUrl(String url) {
        MPJLambdaWrapper<PubReport> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(PubReport.class).innerJoin(SysMenu.class, "men", p -> p.eq(SysMenu::getId, PubReport::getMenuId).eq(SysMenu::getUrl, url).eq(SysMenu::getDelFlag, 0)).eq(PubReport::getDelFlag, 0).eq(PubReport::getIsUse, "0").orderByAsc(PubReport::getEditTime);
        List<PubReport> pubReports = pubReportMapper.selectList(lambdaQueryWrapper);
        if (ToolsUtils.isNotEmpty(pubReports)) {
            return Result.succ(1, "查询成功", pubReports.get(0).getId());
        } else {
            return Result.fail("查询失败");
        }
    }

    @Override
    public Result copyReportByOrgId(OrganizationDTO organizationDTO) {
        String letter = AlphabetArray.Alphabet[organizationDTO.getOrgIndex()];
        pubReportMapper.delete(new LambdaQueryWrapper<PubReport>().eq(PubReport::getOrgId, organizationDTO.getGoalOrgId()));
        List<PubReport> reports = pubReportMapper.selectList(new LambdaQueryWrapper<PubReport>().eq(PubReport::getDelFlag, 0).eq(PubReport::getOrgId, organizationDTO.getSourceOrgId()));
        for (PubReport report : reports) {
            report.setId(letter + report.getId().substring(letter.length()));
            if (StringUtils.isNotBlank(report.getParentId())) {
                report.setParentId(letter + report.getParentId().substring(letter.length()));
            }
            if (StringUtils.isNotBlank(report.getModuleId())) {
                report.setModuleId(letter + report.getModuleId().substring(letter.length()));
            }
            if (StringUtils.isNotBlank(report.getMenuId())) {
                report.setMenuId(letter + report.getMenuId().substring(letter.length()));
            }
            report.setOrgId(organizationDTO.getGoalOrgId());
        }
        pubReportService.saveBatch(reports);

        return Result.succ("操作成功");
    }

    @Override
    public Result getModuleDictList() {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isNotEmpty(dictResult)) {
            List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();
            List<Map<String, Object>> setData = getUniqueModuleData(listToJSONArray(data));
            return Result.succ(setData);
        }
        return Result.fail("请检查业务表单词典设置是否正确");
    }

    public static JSONArray listToJSONArray(List<Map<String, Object>> data) {
        // 创建一个新的JSONArray
        JSONArray jsonArray = new JSONArray();

        // 遍历list中的每个map
        for (Map<String, Object> map : data) {
            // 创建一个JSONObject
            JSONObject jsonObject = new JSONObject();

            // 将map中的键值对添加到JSONObject中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }

            // 将JSONObject添加到JSONArray中
            jsonArray.put(jsonObject);
        }

        return jsonArray;
    }


    public static List<Map<String, Object>> jsonArrayToList(JSONArray jsonArray) {
        List<Map<String, Object>> list = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Map<String, Object> map = new HashMap<>();

            Iterator<String> keysIterator = jsonObject.keys();
            while (keysIterator.hasNext()) {
                String key = keysIterator.next();
                Object value = jsonObject.get(key);
                map.put(key, value);
            }

            list.add(map);
        }

        return list;
    }

    public static JSONArray convertJsonArray(JSONArray inputArray) {
        JSONArray resultArray = new JSONArray();
        JSONObject moduleObj = null;

        for (int i = 0; i < inputArray.length(); i++) {
            JSONObject currentItem = inputArray.getJSONObject(i);
            // 如果当前 moduleId 与上一个不同，则创建新的模块对象
            if (moduleObj == null || !moduleObj.getString("moduleId").equals(currentItem.getString("moduleId"))) {
                if (moduleObj != null) {
                    resultArray.put(moduleObj); // 将上一个模块对象添加到结果数组
                }
                moduleObj = new JSONObject();
                moduleObj.put("moduleId", currentItem.getString("moduleId"));
                moduleObj.put("name", currentItem.getString("moduleName"));
                moduleObj.put("children", new JSONArray());
            }

            // 创建子项对象，并设置相关属性
            JSONObject childItem = new JSONObject();
            childItem.put("commonId", currentItem.getString("commonId"));
            childItem.put("name", currentItem.getString("pointsName"));
            childItem.put("isParentEdit", currentItem.getString("isParentEdit"));
            childItem.put("sx", currentItem.getInt("sx"));
            childItem.put("isEdit", currentItem.getString("isEdit"));
            childItem.put("grade", currentItem.getInt("grade"));
            childItem.put("parentId", currentItem.getString("moduleId"));
            childItem.put("children", JSONObject.NULL); // 或者可以用 new JSONArray()

            // 将子项添加到当前模块的 children 数组中
            moduleObj.getJSONArray("children").put(childItem);
        }

        // 不要忘记将最后一个模块对象添加到结果数组
        if (moduleObj != null) {
            resultArray.put(moduleObj);
        }

        return resultArray;
    }

    public List<PubReport> getChildrenPoints(PubReport a, List<PubReport> pubReports) {
        List<PubReport> result = new ArrayList();
        for (PubReport pubReport : pubReports) {
            SysModule module = moduleMapper.selectById(pubReport.getModuleId());
            pubReport.setModuleName(module.getName());
            SysPoints sysPoints = pointsMapper.selectById(pubReport.getPointsId());
            pubReport.setPointsName(sysPoints.getTitle());
            if (StringUtils.isBlank(pubReport.getParentId())) {
                pubReport.setParentName("");
            }
            if (StringUtils.isNotBlank(pubReport.getParentId()) && pubReport.getParentId().equals(a.getId())) {
                pubReport.setParentName(a.getName());
                result.add(pubReport);
            }
        }
        for (PubReport pubReport : result) {
            pubReport.setChildren(getChildrenPoints(pubReport, pubReports));
        }
        if (result.size() == 0) {
            return new ArrayList<>();
        }
        return result;
    }

    public List<PubReport> getChildrenMenu(PubReport a, List<PubReport> pubReports) {
        List<PubReport> result = new ArrayList();
        for (PubReport pubReport : pubReports) {
            SysModule module = moduleMapper.selectById(pubReport.getModuleId());
            pubReport.setModuleName(module.getName());
            SysMenu sysMenu = menuMapper.selectById(pubReport.getMenuId());
            pubReport.setMenuName(sysMenu.getTitle());
            if (StringUtils.isBlank(pubReport.getParentId())) {
                pubReport.setParentName("");
            }
            if (StringUtils.isNotBlank(pubReport.getParentId()) && pubReport.getParentId().equals(a.getId())) {
                pubReport.setParentName(a.getName());
                result.add(pubReport);
            }
        }
        for (PubReport pubReport : result) {
            pubReport.setChildren(getChildrenMenu(pubReport, pubReports));
        }
        if (result.size() == 0) {
            return new ArrayList<>();
        }
        return result;
    }

    public List<PubReport> getChildrenReportInfoInstrument(PubReport a, List<PubReport> pubReports) {
        List<PubReport> result = new ArrayList();
        for (PubReport pubReport : pubReports) {
            if (StringUtils.isBlank(pubReport.getParentId())) {
                pubReport.setParentName("");
            }
            if (StringUtils.isNotBlank(pubReport.getParentId()) && pubReport.getParentId().equals(a.getId())) {
                pubReport.setParentName(a.getName());
                result.add(pubReport);
            }
        }
        for (PubReport pubReport : result) {
            pubReport.setChildren(getChildrenReportInfoInstrument(pubReport, pubReports));
        }
        if (result.size() == 0) {
            return new ArrayList<>();
        }
        return result;
    }


    public List<Map<String, Object>> getUniqueModuleData(JSONArray jsonArray) {

        // 使用Set来存储唯一的moduleId和moduleName对
        Set<Map<String, Object>> uniqueModulesSet = new HashSet<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            // 获取当前的JSONObject
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            // 提取moduleId和moduleName
            String moduleId = jsonObject.getString("moduleId");
            String moduleName = jsonObject.getString("moduleName");

            // 创建Map来存储当前模块的信息
            Map<String, Object> moduleData = new HashMap<>();
            moduleData.put("id", moduleId);
            moduleData.put("name", moduleName);

            // 添加到Set中以去重
            uniqueModulesSet.add(moduleData);
        }

        // 将Set转换为List并返回
        return new ArrayList<>(uniqueModulesSet);
    }

    @Override
    public Result copyBaseData(OrganizationDTO input) {
        if (CollectionUtils.isEmpty(input.getModuleList())) {
            return Result.fail("没有需要复制的模块");
        }
        if (input.getModuleList().contains("Module")) {
            sysModuleService.copyModuleAndMenuByOrgId(input);
        }
        if (input.getModuleList().contains("Role")) {
            sysRoleService.syncRole(input);
        }
        if (input.getModuleList().contains("SysOption")) {
            sysParamService.copySysParamByOrgId(input);
        }
        if (input.getModuleList().contains("Dictionary")) {
            sysBasDictService.copyDictByOrgId(input);
        }
        if (input.getModuleList().contains("Interface")) {
            sysInterfaceService.copyPasteInterfaceData(input);
        }
        if (input.getModuleList().contains("Rules")) {
            sysRuleSetService.copyRuleByOrgId(input);
        }
        if (input.getModuleList().contains("Report")) {
            pubReportService.copyReportByOrgId(input);
        }
        /*创建管理员用户*/
        if (input.getModuleList().contains("CreateUser")) {
            //sysInterfaceService.copyPasteInterfaceData(input);
            sysUserService.syncUserInfo(input);
        }
        /*检验报告模板设置*/
        if (input.getModuleList().contains("mainInfoConfig")) {
            input.setSuitModule("1");
            wlConfigService.copyWlConfig(input);
        }
        /*微生物模板设置*/
        if (input.getModuleList().contains("bacInfoConfig")) {
            input.setSuitModule("2");
            wlConfigService.copyWlConfig(input);
        }
        //流转节点设置
        if (input.getModuleList().contains("labNodeSetting")) {
            processSetService.copyProcessSetData(input);
        }
        return Result.succ(1, "复制成功", null);
    }

    @Override
    public Result getPyReport(String sampleda, String sampleNo,String rptGroup) {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return null;
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();

        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && "002".equals(map.get("pointsCode"))).collect(Collectors.toList());
        if (ToolsUtils.isEmpty(filteredList)) {
            return null;
        }

        String pointId = filteredList.get(0).get("commonId").toString();
        Timestamp startTime = Timestamp.valueOf(sampleda + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(sampleda + " 23:59:59");

        /*查询是否有图片*/
        LambdaQueryWrapper<BacImageResult> bacImageResultQuery = new LambdaQueryWrapper<>();
        bacImageResultQuery.eq(BacImageResult::getDelFlag, 0);
        bacImageResultQuery.eq(BacImageResult::getSampleNo, sampleNo);
        bacImageResultQuery.eq(BacImageResult::getIsSelected, 1);
        bacImageResultQuery.in(BacImageResult::getRptGroup, rptGroup);
        bacImageResultQuery.ge(BacImageResult::getSampleda, startTime);
        bacImageResultQuery.le(BacImageResult::getSampleda, endTime);
        //bacImageResultQuery.in(BacImageResult::getSampleda, input.getSampleda());

        //增加菌株匹配选择，若菌株号存在，则匹配
        int imgCount = bacImageResultMapper.selectCount(bacImageResultQuery);
        /*计算使用的模板Id,模板名称*/
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        if (imgCount > 0) {
            pubRptQuery.eq(PubReport::getIncludeImages, 1);
        }
        pubRptQuery.eq(PubReport::getIsUse, 1);

        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return null;
        }
        PubReport pubReport = pubReportList.get(0);

        /*查询二级报告发布*/
        LambdaQueryWrapper<BacPublisSecReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(BacPublisSecReport::getSampleda, startTime);
        lambdaQueryWrapper.le(BacPublisSecReport::getSampleda, endTime);
        lambdaQueryWrapper.eq(BacPublisSecReport::getRptGroup, rptGroup);
        lambdaQueryWrapper.eq(BacPublisSecReport::getSampleNo, sampleNo);
        lambdaQueryWrapper.and(p -> p.ne(BacPublisSecReport::getIsCancel, 1).or().isNull(BacPublisSecReport::getIsCancel));
        List<BacPublisSecReport> bacPublisSecReports = bacPublisSecReportMapper.selectList(lambdaQueryWrapper);

        List<ReportPreviewDto> resList = new ArrayList<>();
        List<BacRptOverviewItemDto> rptOverviewItemDtoList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(bacPublisSecReports)) {
            String idsStr = bacPublisSecReports.stream().map(BacPublisSecReport::getId).collect(Collectors.joining(","));
            ReportPreviewDto _m = new ReportPreviewDto();
            _m.setId(idsStr);
            _m.setReportId(pubReport.getId());
            _m.setIsChecked(true);
            _m.setReportTemplateName(pubReport.getName());
            resList.add(_m);
        }
        return Result.succ(1, "查询成功", resList);
    }

    @Override
    public Result againReqNo() {
        /*计算使用哪个模板*/
        /*计算使用的模板Id,模板名称*/
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return Result.fail("未找到相关字典数据");
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();
        String finalReportCode = "againReqNo";
        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1747828187831173122".equals(map.get("moduleId")) && (finalReportCode.equals(map.get("pointsCode")))).collect(Collectors.toList());//阴性报告
        if (ToolsUtils.isEmpty(filteredList)) {
            return Result.fail("未找到相关字典数据");
        }
        String pointId = filteredList.get(0).get("commonId").toString();
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        pubRptQuery.eq(PubReport::getIsUse, 1);
        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return Result.fail("未找到重打条码相关模板数据");
        }
        return Result.succ(1, "查询成功", pubReportList.get(0));
    }

    @Override
    public Result againLable() {
        /*计算使用哪个模板*/
        /*计算使用的模板Id,模板名称*/
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return Result.fail("未找到相关字典数据");
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();
        String finalReportCode = "againLable";
        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1747828187831173122".equals(map.get("moduleId")) && (finalReportCode.equals(map.get("pointsCode")))).collect(Collectors.toList());//阴性报告
        if (ToolsUtils.isEmpty(filteredList)) {
            return Result.fail("未找到相关字典数据");
        }
        String pointId = filteredList.get(0).get("commonId").toString();
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        pubRptQuery.eq(PubReport::getIsUse, 1);
        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return Result.fail("未找到重打标签相关模板数据");
        }
        return Result.succ(1, "查询成功", pubReportList.get(0));
    }

    @Override
    public Result print() {
        /*计算使用哪个模板*/
        /*计算使用的模板Id,模板名称*/
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return Result.fail("未找到相关字典数据");
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();
        String finalReportCode = "samplePrint";
        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1747828187831173122".equals(map.get("moduleId")) && (finalReportCode.equals(map.get("pointsCode")))).collect(Collectors.toList());//阴性报告
        if (ToolsUtils.isEmpty(filteredList)) {
            return Result.fail("未找到相关字典数据");
        }
        String pointId = filteredList.get(0).get("commonId").toString();
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        pubRptQuery.eq(PubReport::getIsUse, 1);
        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return Result.fail("未找到打印相关模板数据");
        }
        return Result.succ(1, "查询成功", pubReportList.get(0));
    }


}
